package com.ErpCoreWeb.Security.Access;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.AccessType;
import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CDesktopGroupAccessInRole;
import com.ErpCoreModel.Base.CDesktopGroupAccessInUser;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CDesktopGroup;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class DesktopGroupAccessPanel
 */
@WebServlet("/DesktopGroupAccessPanel")
public class DesktopGroupAccessPanel extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CCompany m_Company = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DesktopGroupAccessPanel() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
        String B_Company_id = request.getParameter("B_Company_id");
		if (Global.IsNullParameter(B_Company_id))
			m_Company = Global.GetCtx(this.getServletContext())
					.getCompanyMgr().FindTopCompany();
		else
			m_Company = (CCompany) Global.GetCtx(this.getServletContext())
					.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
	
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
		
	}

    void GetData()
    {
    	String UType = request.getParameter("UType");
        String Uid =  request.getParameter("Uid");
        if(Global.IsNullParameter(UType)
        		|| Global.IsNullParameter(Uid))
        	return ;
        CUser user = null;
        CRole role = null;
        if (UType.equals( "0")) //用户
        {
            if (!Global.IsNullParameter(Uid))
            {
                user = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(Util.GetUUID(Uid));
            }
        }
        else if (UType.equals( "1")) //角色
        {
            if (!Global.IsNullParameter(Uid))
            {
                role = (CRole)m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
            }
        }

        String sData = "";
        List<CBaseObject> lstObj = Global.GetCtx(this.getServletContext()).getDesktopGroupMgr().GetList();

        for (CBaseObject obj : lstObj)
        {
            CDesktopGroup group = (CDesktopGroup)obj;
            int iRead = 0;
            int iWrite = 0;
            if (UType.equals("0") && user!=null) //用户
            {
                //管理员有所有权限
                if (user.IsRole("管理员"))
                {
                    iRead = 1;
                    iWrite = 1;
                }
                else
                {
                    CDesktopGroupAccessInUser dgaiu = user.getDesktopGroupAccessInUserMgr().FindByDesktopGroup(group.getId());
                    if (dgaiu != null)
                    {
                        if (dgaiu.getAccess() == AccessType.read)
                            iRead = 1;
                        else if (dgaiu.getAccess() == AccessType.write)
                        {
                            iRead = 1;
                            iWrite = 1;
                        }
                    }
                }
            }
            else if (UType.equals( "1") && role != null) //用户
            {
                //管理员有所有权限
                if (role.getName().equalsIgnoreCase( "管理员"))
                {
                    iRead = 1;
                    iWrite = 1;
                }
                else
                {
                    CDesktopGroupAccessInRole dgair = role.getDesktopGroupAccessInRoleMgr().FindByDesktopGroup(group.getId());
                    if (dgair != null)
                    {
                        if (dgair.getAccess() == AccessType.read)
                            iRead = 1;
                        else if (dgair.getAccess() == AccessType.write)
                        {
                            iRead = 1;
                            iWrite = 1;
                        }
                    }
                }
            }
            String sRow = String.format("\"id\":\"%s\",\"Name\":\"%s\",\"Read\":\"%d\",\"Write\":\"%d\",", group.getId().toString(), group.getName(), iRead, iWrite);

            sRow = "{" + sRow + "},";
            sData += sRow;
        }
        if(sData.length()>0 && sData.endsWith(","))
        	sData = sData.substring(0, sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, lstObj.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void PostData()
    {
		try {
			String UType = request.getParameter("UType");
			String Uid = request.getParameter("Uid");
			String postData = request.getParameter("postData");
	        if(Global.IsNullParameter(UType)
	        	|| Global.IsNullParameter(Uid)
        		|| Global.IsNullParameter(postData))
	        	return ;
			CUser user = null;
			CRole role = null;
			if (UType.equals("0")) // 用户
			{
				user = (CUser) Global.GetCtx(this.getServletContext())
						.getUserMgr().Find(Util.GetUUID(Uid));
				// 管理员有所有权限，不能修改！
				if (user.IsRole("管理员")) {
					response.getWriter().print("管理员有所有权限，不能修改！");
					return;
				}
				//
				String[] arr1 = postData.split(";");
				for (String sItem1 : arr1) {
					String[] arr2 = sItem1.split(",");
					UUID groupid = Util.GetUUID(arr2[0]);
					CDesktopGroupAccessInUser dgaiu = user
							.getDesktopGroupAccessInUserMgr()
							.FindByDesktopGroup(groupid);
					if (dgaiu == null) {
						dgaiu = new CDesktopGroupAccessInUser();
						dgaiu.setUI_DesktopGroup_id(groupid);
						dgaiu.setB_User_id(user.getId());
						if (arr2[2].equals("1"))
							dgaiu.setAccess(AccessType.write);
						else if (arr2[1].equals("1"))
							dgaiu.setAccess(AccessType.read);
						else
							dgaiu.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						dgaiu.setUpdator(user0.getId());
						user.getDesktopGroupAccessInUserMgr().AddNew(dgaiu);
					} else {
						if (arr2[2].equals("1"))
							dgaiu.setAccess(AccessType.write);
						else if (arr2[1].equals("1"))
							dgaiu.setAccess(AccessType.read);
						else
							dgaiu.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						dgaiu.setUpdator(user0.getId());
						user.getDesktopGroupAccessInUserMgr().Update(dgaiu);
					}
				}
				if (!user.getDesktopGroupAccessInUserMgr().Save(true)) {
					response.getWriter().print("保存失败！");
				}
			} else if (UType.equals("1")) // 角色
			{
				role = (CRole) m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
				// 管理员有所有权限，不能修改！
				if (role.getName().equalsIgnoreCase("管理员")) {
					response.getWriter().print("管理员有所有权限，不能修改！");
					return;
				}
				//
				String[] arr1 = postData.split(";");
				for (String sItem1 : arr1) {
					String[] arr2 = sItem1.split(",");
					UUID groupid = Util.GetUUID(arr2[0]);
					CDesktopGroupAccessInRole dgair = role
							.getDesktopGroupAccessInRoleMgr()
							.FindByDesktopGroup(groupid);
					if (dgair == null) {
						dgair = new CDesktopGroupAccessInRole();
						dgair.setUI_DesktopGroup_id(groupid);
						dgair.setB_Role_id(role.getId());
						if (arr2[2].equals("1"))
							dgair.setAccess(AccessType.write);
						else if (arr2[1].equals("1"))
							dgair.setAccess(AccessType.read);
						else
							dgair.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						dgair.setCreator(user0.getId());
						role.getDesktopGroupAccessInRoleMgr().AddNew(dgair);
					} else {
						if (arr2[2].equals("1"))
							dgair.setAccess(AccessType.write);
						else if (arr2[1].equals("1"))
							dgair.setAccess(AccessType.read);
						else
							dgair.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						dgair.setUpdator(user0.getId());
						role.getDesktopGroupAccessInRoleMgr().Update(dgair);
					}
				}
				if (!role.getDesktopGroupAccessInRoleMgr().Save(true)) {
					response.getWriter().print("保存失败！");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
